package com.gzsxy.sso.resources.handler;


import com.gzsxy.sso.resources.web.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 注销成功自定义处理
 * @date 2021/11/8 11:30
 */
@Component
public class CustomLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth) throws IOException, ServletException {

        Result result = null;
        try {
            //获取token
            String access_token = req.getParameter("access_token");
            if (!StringUtils.isEmpty(access_token)){
                //读取token
                OAuth2AccessToken token = tokenStore.readAccessToken(access_token);
                if (token != null ){
                    tokenStore.removeAccessToken(token);
                    res.setStatus(HttpServletResponse.SC_OK);
                    result = Result.success("注销成功");
                } else {
                    result = Result.error("注销失败！无法获取对应的凭证，可能已经注销").simplify();
                }
            } else {
                result = Result.error("注销失败！ 无法获取access_token");
            }
        } catch (Exception e) {
           result = Result.error("注销时发生异常！ 异常信息:"+e.getMessage());
        }
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/json");
        PrintWriter print = res.getWriter();
        //写入到响应体中
        print.write(result.toJSONString());
        print.flush();
        print.close();
    }
}
